package com.ck.company.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ck.constant.ProgramSourceTypeEnum;
import com.ck.model.common.Scene;
import com.ck.model.common.SceneSource;
import com.ck.model.common.ScreenCanvasMapping;
import com.ck.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 节目json解析工具类
 * <p>
 * 节目json结构如下：
 * <p>
 * {
 * // 模板ID
 * programTemplateId: null,
 * // 节目ID
 * programId: null,
 * <p>
 * json: {
 * // 屏幕分辨率
 * screenWidth: 1080,
 * screenHeight: 1920,
 * <p>
 * // 画布大小
 * canvasWidth: 320,
 * canvasHeight: 568,
 * <p>
 * // 投放开始时间
 * putinStartTime: 2534244812000,
 * // 投放结束时间：
 * putinEndTime: 2534331212000,
 * <p>
 * // 场景
 * scenes: [{
 * // 场景名称
 * name: '场景1',
 * // 场景时长(毫秒)
 * duration: 30 * 1000,
 * <p>
 * // 分组
 * groups: [{
 * top: 100,
 * left: 100,
 * width: 100,
 * height: 100,
 * <p>
 * // 模块
 * modules: [{
 * name: '场景1节目1',
 * // 模块类型 0、视频 1、图片
 * type: 0,
 * // 时长（毫秒）
 * duration: 5 * 1000,
 * // 图片和视频
 * url: '',
 * md5: '',
 * <p>
 * //单位字节
 * size: 0,
 * <p>
 * // 二维码模块
 * qr: {
 * link: '二维码链接',
 * title: '二维码标题',
 * }
 * },
 * {
 * name: '场景1节目2',
 * // 模块类型 0、视频 1、图片
 * type: 0,
 * // 模块时长(毫秒)
 * duration: 5 * 1000,
 * <p>
 * md5: '',
 * <p>
 * //单位字节
 * size: 0,
 * <p>
 * // 动态参数
 * // 图片和视频
 * url: '',
 * <p>
 * // 二维码模块
 * qr: {
 * link: '二维码链接',
 * title: '二维码标题',
 * }
 * },
 * ]
 * },
 * <p>
 * ],
 * },
 * <p>
 * {
 * // 场景名称
 * name: '场景2',
 * // 场景时长(毫秒)
 * duration: 30 * 1000,
 * <p>
 * // 分组
 * groups: [{
 * top: 300,
 * left: 100,
 * width: 100,
 * height: 100,
 * // 模块
 * modules: [{
 * name: '场景2节目1',
 * // 模块类型 0、视频 1、图片
 * type: 0,
 * // 模块时长(毫秒)
 * duration: 5 * 1000,
 * <p>
 * // 动态参数
 * // 图片和视频
 * url: '',
 * <p>
 * md5: '',
 * <p>
 * //单位字节
 * size: 0,
 * <p>
 * // 二维码模块
 * qr: {
 * link: '二维码链接',
 * title: '二维码标题',
 * }
 * }]
 * },
 * <p>
 * ],
 * }
 * ],
 * }
 * <p>
 * }
 *
 * @author linqiang
 * @version v1.0
 * @date 2018-09-12 15:01
 */
@Service("programParseService")
public class ProgramParseService {

    @Autowired
    private CpScreenCanvasMappingService cpScreenCanvasMappingService;

    /**
     * 从节目json中获取场景信息
     *
     * @param programJson 节目json
     * @return 场景集合
     */
    public Map<String, Object> getProgramDataFromJson(String programJson) {
        Map<String, Object> result = new HashMap<>(3);
        if (StringUtils.isBlank(programJson)) {
            return null;
        }
        List<Scene> sceneList = new ArrayList<>();
        List<SceneSource> sceneSourceList = new ArrayList<>();
        Integer canvasWidth = 0;
        Integer canvasHeight = 0;
        Integer screenWidth = 0;
        Integer screenHeight = 0;
        JSONObject program = JSONObject.parseObject(programJson);
        long programSize = 0L;
        Integer programDuration = 0;
        long now = System.currentTimeMillis();
        if (null != program) {
            //根据屏幕分辨率宽高获取画布宽高
            screenWidth = program.getInteger("screenWidth");
            screenHeight = program.getInteger("screenHeight");
            if (screenWidth != null && screenHeight != null) {
                ScreenCanvasMapping screenCanvasMapping = cpScreenCanvasMappingService.selectByScreen(screenWidth, screenHeight);
                if (screenCanvasMapping != null) {
                    canvasWidth = screenCanvasMapping.getCanvasWidth();
                    canvasHeight = screenCanvasMapping.getCanvasHeight();
                }
            }
            //场景数组
            JSONArray scenes = program.getJSONArray("scenes");
            if (null != scenes && scenes.size() > 0) {
                for (int i = 0; i < scenes.size(); i++) {
                    JSONObject scenesJSONObject = scenes.getJSONObject(i);
                    if (null != scenesJSONObject) {
                        Scene scene = new Scene();
                        //场景名称
                        String sceneName = scenesJSONObject.getString("name");
                        //时长（毫秒）
                        Integer sceneDuration = scenesJSONObject.getInteger("duration");
                        String background = scenesJSONObject.getString("background");
                        if (StringUtils.isNotBlank(sceneName) && sceneDuration > 0) {
                            programDuration += sceneDuration;
                            scene.setSceneName(sceneName);
                            scene.setSceneDuration(sceneDuration);
                            String sceneVersion = UUIDUtils.getUUIDString();
                            scene.setSceneVersion(sceneVersion);
                            scene.setAddTime(now);
                            scene.setBackground(background);
                            //获取分组
                            JSONArray groups = scenesJSONObject.getJSONArray("groups");
                            if (null != groups && groups.size() > 0) {
                                for (int j = 0; j < groups.size(); j++) {
                                    JSONObject group = groups.getJSONObject(j);
                                    if (null != group) {
                                        //获取模块(素材)
                                        JSONArray modules = group.getJSONArray("modules");
                                        if (null != modules && modules.size() > 0) {
                                            for (int k = 0; k < modules.size(); k++) {
                                                JSONObject module = modules.getJSONObject(k);
                                                String moduleName = module.getString("name");
                                                Integer type = module.getInteger("type");
                                                Long duration = module.getLong("duration");
                                                Long size = module.getLong("size");
                                                String md5 = module.getString("md5");
                                                String url = getUrlFromModule(module);
                                                if (null != size) {
                                                    programSize += size;
                                                }
                                                if (StringUtils.isNotBlank(url) && null != duration && duration > 0 && size > 0) {
                                                    SceneSource source = new SceneSource(null, sceneVersion, url, md5, now, null);
                                                    sceneSourceList.add(source);
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                            sceneList.add(scene);
                        }
                    }
                }
            }
        }
        result.put("sceneList", sceneList);
        result.put("sceneSourceList", sceneSourceList);
        result.put("programSize", programSize);
        result.put("programDuration", programDuration);
        result.put("canvasWidth", canvasWidth);
        result.put("canvasHeight", canvasHeight);
        result.put("screenWidth", screenWidth);
        result.put("screenHeight", screenHeight);
        return result;
    }

    /**
     * 从模块中获取连接地址
     *
     * @param module 模块
     * @return 地址
     */
    private static String getUrlFromModule(JSONObject module) {
        if (null == module) {
            return "";
        }
        String url = "";
        Integer type = module.getInteger("type");
        if (null != type) {
            if (ProgramSourceTypeEnum.IMAGE.getType().equals(type)) {
                //图片
                url = module.getString("url");
            } else if (ProgramSourceTypeEnum.VIDEO.getType().equals(type)) {
                //视频
                url = module.getString("url");
            } else if (ProgramSourceTypeEnum.QR_CODE.getType().equals(type)) {
                //二维码
                JSONObject qr = module.getJSONObject("qr");
                if (null != qr) {
                    url = qr.getString("link");
                }
            } else if (ProgramSourceTypeEnum.AUDIO.getType().equals(type)) {
                //音频
                url = module.getString("url");
            }
        }
        return url;
    }
}
